import { getLocale, history } from 'umi';
import {
  request,
  getToken,
  getRawToken,
  setToken,
  removeToken,
  setDict,
  setAuthorities,
} from '@/zero';

/**
 * 初始结构
 */
const initialState = {
  currentUser: {}, // 当前用户
  collapsed: false, // 是否收起侧边栏
};

export default {
  namespace: 'global.remote',

  state: initialState,

  effects: {
    /**
     * 获取当前用户信息
     */
    *setCurrentUser(_, { call, put, all }) {
      if (getToken()) {
        const [response, { data: currentCompany = {} }, { data: currentSecurity = {} }] = yield all(
          [
            call(request, '/server/api/companys/get/one'),
            call(request, '/server/api/ldapconfigs'),
            call(request, '/server/api/users/userinfo'),
          ],
        );

        yield put({
          type: 'save',
          payload: {
            currentUser: {
              ...response.data,
              logo: `/sso/api/products/logo/transonline?token=${getToken()}`,
              company: currentCompany,
              security: currentSecurity,
            },
          },
        });
        return response;
      }
      return null;
    },

    /**
     * 用户登录 => 账号登录
     */
    *userLogin({ payload }, { call, put }) {
      const response = yield call(request, `/server/api/users/login`, {
        method: 'post',
        body: {
          appType: 0, // warning
          ...payload,
        },
      }); // 进行登录
      if (response.success) {
        const { token } = response.data;

        setToken(token); // 设置“Token” => 后端服务

        setAuthorities(['000', '001', '002', '003', '100', '101', '102', '103']);

        yield put.resolve({
          type: 'setDict',
        }); // put 同步执行

        yield put({
          type: 'save',
          payload: {
            currentUser: {
              ...response.data,
            },
          },
        });
      }

      return response;
    },

    *ssoLogin({ payload }, { put, call }) {
      setToken(`${payload.token}##${payload.main}##SSO`);

      const { data: authority = [] } = yield call(
        request,
        `/server/api/users/getaliasnames?productUid=pdffixer`,
        {
          method: 'get',
          body: { token: payload.token },
        },
      );
      setAuthorities(authority.map((item) => `${item.id}`));

      yield put.resolve({
        type: 'setCurrentUser',
      });
      yield put.resolve({
        type: 'setDict',
      });
    },

    /**
     * 退出登录
     */
    *userLogout(_, { put }) {
      const rawToken = getRawToken();

      removeToken(); // 移除“Token”
      setAuthorities([]);
      yield put({ type: 'save', payload: { currentUser: {} } }); // 清空登录信息

      if (rawToken?.endsWith('SSO')) {
        window.location.href =
          rawToken.split('##')[1] || 'https://cloud-dev.dip-aitech.com/product-list';
      } else {
        history.push('/g/login');
      }
    },

    /**
     * 获取数据字典
     */
    *setDict({ payload }, { call, all }) {
      const newLang = (payload?.lang || getLocale()) === 'en-US' ? 'en' : 'zh';

      const [
        { data: dictInstance }, // 获取全部数据字典
        { data: icsrDictInstance }, // 获取 ICSR 数据字典
        { data: adrDictInstance }, // 获取 ADR 数据字典
      ] = yield all([
        call(request, '/pv/api/sysdicts/findwebdict', {
          method: 'get',
          body: {
            type: 1,
            language: newLang,
          },
        }),
        call(request, '/pv/api/sysdicts/findwebdict', {
          method: 'get',
          body: {
            type: 2,
            language: newLang,
          },
        }),
        call(request, '/pv/api/sysdicts/findwebdict', {
          method: 'get',
          body: {
            type: 3,
            language: newLang,
          },
        }),
      ]);

      setDict(dictInstance, icsrDictInstance, adrDictInstance);
    },

    *setCollapsed({ payload }, { put }) {
      return yield put({ type: 'save', payload });
    },

    *resetPassword({ payload }, { call }) {
      const response = yield call(request, `/server/api/users/${payload.id}/updatepassword`, {
        method: 'put',
        body: payload,
      });
      return response;
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },

  subscriptions: {
    setup(params) {
      // Subscribe history(url) change, trigger `load` action if pathname is `/`
      return params.history.listen(({ pathname, search }) => {
        if (typeof window.ga !== 'undefined') {
          window.ga('send', 'pageview', pathname + search);
        }
      });
    },
  },
};
